<template>
    <div
        class='selection'
        ref='selection'
        @mouseup="selectionMouseUp($event)"
        @mousedown="selectionMouseDown($event)"
        @mousemove="selectionMouseMove($event)"
        @click="selectionClick($event)"
        :style="{ width: width ? `${width+30}px`: null, position: position, }"
    >
        <slot></slot>

        <div
            v-show="(this.mouse.top!==0 && this.mouse.left!==0 && copyResultText !== '' && !btnStatus && this.switch )"
            class='selection-btn'
            :style="{top:`${this.mouse.top}px`, left: `${this.mouse.left}px`,}"
            @click="copyResult"
            @mousedown="copyResultDown($event)"
        >
            <vi-icon type="copy" class='selection-btn-icon'></vi-icon>
            复制
        </div>

        <textarea v-show="copyResultText !== ''" class="identifyResult-hidden" :id="keyId">{{copyResultText}}</textarea>

    </div>
</template>

<script>
import activeShowMixin from "../../mixin/activeShow.mixin";
import $ from 'jquery';

export default {
    name: 'selection', // 组件名称
    mixins: [activeShowMixin], // 组件插件 可插入方法（全局方法或生命周期方法）
    props: { // 有父组件传递而来 参数有类型区分
        keyId: {
            type: String,
            default: 'sel-identifyResult',
        },
        auxPosition: {
            type: Object,
            default: function () {
                return {top: '0px', left: '0px'};
            },
        },
        width: {
            type: Number,
            default: 0,
        },
        position: {
            type: String,
            default: 'relative',
        },
        // 文字复制成功回掉函数
        copyCallback: {
            type: Function,
            default: function () {
                return false;
            },
        },
        // 是否开启功能
        switch: {
            type: Boolean,
            default: true,
        },
        // 是否是表格模式
        showOcrTable: {
            type: Boolean,
            default: false,
        },
    },
    data() { // 组件内数据 仅可在当前组件内修改和使用
        return {
            mouse: {top: 0, left: 0}, // 当前鼠标位置
            copyResultText: '',
            btnStatus: false, // 是否点击了全选 ctry+a true； 活动 false；
            mouseDown: {top: 0, left: 0}, // 鼠标落地位置
        }
    },
    mounted() { // 生命周期
        let that = this;
        $(document).keydown(function(event){
            // event.keyCode 65 a键
            if (event.ctrlKey && event.keyCode == 65){
                that.btnStatus = true;
                that.copyResultText = '';
                this.mouse = {top: 0, left: 0};
                // console.log('keydown', event.ctrlKey, event.keyCode, that.btnStatus );
            }
        });
    },
    watch: { // 数据监听，任何变化，都会触发这里面的方法，实现数据变化，牵引其他逻辑变化
        mouse:function (val, oldVal) {
            if(val.top && val.left && this.copyResultText!=='' && !this.btnStatus ){
                this.setSelectionBtnVisible(true);
            }
            else{
                this.setSelectionBtnVisible(false);
            }
        },
        copyResultText:function (val, oldVal) {
            if(val!=='' && this.mouse.top && this.mouse.left && !this.btnStatus ){
                this.setSelectionBtnVisible(true);
            }
            else{
                this.setSelectionBtnVisible(false);
            }
        },
        btnStatus:function (val, oldVal) {
            if(!val && this.mouse.top && this.mouse.left && this.copyResultText!=='' ){
                this.setSelectionBtnVisible(true);
            }
            else{
                this.setSelectionBtnVisible(false);
            }
        },
        selectionBtnVisible:function (val, oldVal) {
            if(!val && oldVal ){
                this.mouse = {top: 0, left: 0} // 当前鼠标位置
                this.$refs.selection.focus() //解决ff不获取焦点无法定位问题
                var range = window.getSelection();//创建range
                range.selectAllChildren(this.$refs.selection);//range 选择obj下所有子内容
                range.collapseToEnd();
            }
        },
        auxPosition:function (val, oldVal) {
            console.log( 'auxPosition', val  );
            if(val.top !== '0px' && val.left !== '0px' ){
                let top = val.top;
                let left = val.left;
                // console.log(val, parseInt( top.substring(0, top.length-2 ) ), parseInt( left.substring(0, left.length-2 ) ) );
                this.mouse = {
                    top: parseInt( top.substring(0, top.length-2 ) ),
                    left: parseInt( left.substring(0, left.length-2 ) ),
                }
            }
            else{
                this.mouse = {top: 0, left: 0} // 当前鼠标位置
                this.$refs.selection.focus() //解决ff不获取焦点无法定位问题
                var range = window.getSelection();//创建range
                range.selectAllChildren(this.$refs.selection);//range 选择obj下所有子内容
                range.collapseToEnd();
                this.setSelectionBtnVisible(false);
            }
        },
        switch:function (val, oldVal) {
            // console.log('switch', val, this.mouse, window.getSelection().toString() , this.copyResultText, this.btnStatus );
            if(val && window.getSelection().toString() !== '' ){
                this.copyResultText = window.getSelection().toString().replace(/^\s*|\s*$/g,"");
            }
            else{
                this.mouse = {top: 0, left: 0} // 当前鼠标位置
                this.$refs.selection.focus() //解决ff不获取焦点无法定位问题
                var range = window.getSelection();//创建range
                range.selectAllChildren(this.$refs.selection);//range 选择obj下所有子内容
                range.selectAllChildren(this.$refs.selection)&&range.collapseToEnd();
                this.setSelectionBtnVisible(false);
            }
        },
    },
    computed: { // 计算属性，当计算属性内用到的数据发生变化，就会触发方法，前提，该数据在页面有读取使用。 1.可将几个数据按照一定关系返回新数据 2.可返回vuex中的数据
        // 拖动选择的按钮展示隐藏
        selectionBtnVisible() {
            return this.$store.state.status.selectionBtnVisible;
        },
    },
    methods: { // 方法 全是自定义的方法
        // 当前鼠标位置
        getMouseFun(event){
            let mouse = {
                top: event.layerY||0,
                left: event.layerX||0,
            }
            // console.log(event);
            return mouse;
        },
        // 复制当前选中内容
        copyResult() {
            let dom = document.getElementById(this.keyId);
            // console.log(dom);
            dom.select(); // 选择对象
            document.execCommand("Copy");
            this.setFileEdit(0);

            if(document.execCommand("Copy")){
                this.$message.success(`文字复制成功！`);
                this.copyCallback();
            }else{
                this.$message.warning(`文字复制失败！`);
            }

            this.mouse = {top: 0, left: 0}; // 当前鼠标位置
        },
        copyResultDown(event){
            event.stopPropagation();

            // 复制按钮上面点右击
            if(event.button == 2){
                this.copyResultText = '';
            }
        },
        // 获取拖动区域文本
        selectionMouseUp(event) {
            console.log( 'selectionMouseUp', window.getSelection().toString(), event );

            // 空编辑
            if( !this.switch ){
                event.stopPropagation();
                return
            }

            if(event.button == 2){
                if(window.getSelection().toString() == '' ){
                    this.copyResultText = '';
                    this.mouse = {top: 0, left: 0};
                    this.$refs.selection.focus() //解决ff不获取焦点无法定位问题
                    var range = window.getSelection();//创建range
                    range.selectAllChildren(this.$refs.selection);//range 选择obj下所有子内容
                    range.collapseToEnd();
                }
                else{
                    let mouse = this.getMouseFun(event);
                    mouse.top = mouse.top + 30;
                    this.mouse = mouse;
                    this.copyResultText = window.getSelection().toString().replace(/^\s*|\s*$/g,"");
                }
                return
            }

            if(window.getSelection().toString() !== '' && !this.btnStatus ){
                let mouse = this.getMouseFun(event);
                // console.log( 'selectionMouseUp', window.getSelection().toString(), this.copyResultText, mouse, this.mouse, this.mouseDown );
                // 在同一选择区域点击
                if( this.copyResultText == window.getSelection().toString() &&
                    mouse.top !== this.mouse.top &&
                    mouse.left !== this.mouse.left &&
                    event.button !== 2 &&
                    this.mouse.top !== 0 &&
                    this.mouse.left !== 0
                ){
                    this.copyResultText = '';
                    this.mouse = {top: 0, left: 0};
                    this.$refs.selection.focus() //解决ff不获取焦点无法定位问题
                    var range = window.getSelection();//创建range
                    range.selectAllChildren(this.$refs.selection);//range 选择obj下所有子内容
                    range.collapseToEnd();
                    return
                }

                // 在同一点点击
                if( mouse.top == this.mouseDown.top &&
                    mouse.left == this.mouseDown.left
                ){
                    this.copyResultText = '';
                    this.mouse = {top: 0, left: 0};
                    this.$refs.selection.focus() //解决ff不获取焦点无法定位问题
                    var range = window.getSelection();//创建range
                    range.selectAllChildren(this.$refs.selection);//range 选择obj下所有子内容
                    range.collapseToEnd();
                    return
                }

                mouse.top = mouse.top + 30;
                this.mouse = mouse;
                this.copyResultText = window.getSelection().toString().replace(/^\s*|\s*$/g,"");
                if( this.showOcrTable ){
                    this.setFileEdit(2);
                }
            }
            else{
                this.copyResultText = '';
                this.mouse = {top: 0, left: 0};
                this.$refs.selection.focus() //解决ff不获取焦点无法定位问题
                var range = window.getSelection();//创建range
                range.selectAllChildren(this.$refs.selection);//range 选择obj下所有子内容
                range.selectAllChildren(this.$refs.selection) && range.collapseToEnd();
            }
        },
        // 鼠标落下
        selectionMouseDown(event){
            // console.log( 'selectionMouseDown', window.getSelection().toString(), event );

            // 空编辑
            if( !this.switch ){
                event.stopPropagation();
                return
            }

            // 全选清除
            if( this.btnStatus && window.getSelection() && this.$refs.selection ){
                // 解决页面全选持续问题
                this.$refs.selection.focus() //解决ff不获取焦点无法定位问题
                var range = window.getSelection();//创建range
                range.selectAllChildren(this.$refs.selection);//range 选择obj下所有子内容
                range.collapseToEnd();
                this.btnStatus = false;
            }
        },
        // 鼠标滑动
        selectionMouseMove(event){
            // console.log( 'selectionMouseMove', window.getSelection().toString(), event );
            // 空编辑
            if( !this.switch ){
                event.stopPropagation();
                return
            }
        },
        // 鼠标点击
        selectionClick(event){
            // console.log( 'selectionClick', window.getSelection().toString(), event );
            // 空编辑
            if( !this.switch ){
                event.stopPropagation();
                return
            }
        },
    },
}
</script>

<style lang="less" scoped>
.selection{
    -webkit-user-select:text;
    -moz-user-select:text;
    -ms-user-select:text;
    user-select: text;
    padding: 15px;
}

.selection-btn{
    position: absolute;
    height: 32px;
    line-height: 32px;
    width: 60px;
    border: 1px solid #dcdcdc;
    border-radius: 3px;
    background-color: #fff;
    text-align: center;
    font-size: 14px;
    cursor: pointer;
    -webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select: none;
    &:hover{
        color: @primary;
    }
}

.selection-btn-icon{
    &:hover{
        color: @primary;
    }
}

.identifyResult-hidden{
    width: 0;
    height: 0;
    overflow: hidden;
    border-color: transparent;
    padding: 0px;
    margin: 0px;
    z-index: 0;
    position: absolute;
}

</style>
